<script lang="ts" setup>
import { onMounted, ref } from "vue"
import record from "@/utils/record.ts"
import { APITextRand } from "@/api/ApiSpeechModel"

const recwave = ref(null)
const recording = ref(false)
const audioUrl = ref("")
const text = ref("")
const emits = defineEmits(["callback"])
/**初始化 */
function recInit() {
  record.getPermission(function (permiss: any) {
    if (permiss.status == "fail") {
      console.log(permiss)
    } else {
      record.startRecorder()
      recording.value = true
    }
  }, recwave.value)
}

/**结束录音 */
function stopRec() {
  record.stopRecorder(function (res: any) {
    /**处理 */
    console.log(res)
    audioUrl.value = res.url
    recording.value = false
    emits("callback", res.blob) //结束回调
  })
}

// defineExpose({
//   recOpen
// })

onMounted(async () => {
  const { data, code } = await APITextRand()
  console.log(data, code)
  if (code === 200) {
    text.value = data.text
  }
})
</script>

<template>
  <div class="app-container">
    <div class="wave-bt">
      <!-- 打开录音请求权限 -->
      <!-- <el-button @click="recOpen" :icon="User" circle /> -->
      <!-- 开始录音 -->
      <el-button color="#f3efef" circle>
        <el-icon v-if="!recording" @click="recInit"><CaretRight /></el-icon>
        <el-icon v-else @click="stopRec"><Mic /></el-icon>
      </el-button>
      <!-- 结束录音 -->
      <!-- <el-button @click="recStop" :icon="VideoPlay" circle /> -->
      <!-- 本地试听 -->
      <!-- <el-button @click="recPlay" :icon="Download" circle /> -->
      <audio class="audio" v-if="audioUrl" ref="audio" controls :src="audioUrl" />
    </div>

    <!-- 波形绘制区域 -->
    <div class="wave-container">
      {{ text }}
      <div class="wave" ref="recwave" />
    </div>
  </div>
</template>
<style lang="scss" scoped>
.wave-container {
  border: 1px solid #ccc;
  border-radius: 4px;
  padding: 10px;
  display: inline-block;
  vertical-align: bottom;
  .wave {
    height: 100px;
    width: 300px;
  }
}
.wave-bt {
  display: flex;
  text-align: center;
  padding-bottom: 20px;
  .el-button {
    // background: #f3efef;
    height: 32px;
    margin-right: 10px;
    color: #333;
  }
}
.audio {
  height: 32px;
}
</style>
